package com.netty.rpc.server.handler;

import com.netty.rpc.message.RpcRequestMessage;
import com.netty.rpc.message.RpcResponseMessage;
import com.netty.rpc.server.factory.DefaultServiceFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        RpcResponseMessage rpcResponseMessage = new RpcResponseMessage();
        try {
            // 处理事件
            Class<?> clazz = Class.forName(msg.getInterfaceName());
            Object bean = DefaultServiceFactory.build().getBean(clazz);
            // 执行方法
            Method method = clazz.getMethod(msg.getMethodName(), msg.getParameterTypes());
            Object value = method.invoke(bean, msg.getParameterValue());
            rpcResponseMessage.setSequenceId(msg.getSequenceId());
            rpcResponseMessage.setReturnValue(value);
        }catch (Exception e){
            e.printStackTrace();
            rpcResponseMessage.setExceptionValue(new Exception(e.getCause().getMessage()));
        }
        ctx.writeAndFlush(rpcResponseMessage);
    }
}
